package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;
import com.xsherl.leetcode.utils.PrintUtils;

public class SearchInRotatedSortedArray {

    /**
     * 先计算旋转的长度
     * 然后采用二分查找法，mid都减去旋转长度就为当前的实际下标
     *
     * @param nums
     * 1 <= nums.length <= 5000
     * -10^4 <= nums[i] <= 10^4
     * nums 中的每个值都 独一无二
     * 题目数据保证 nums 在预先未知的某个下标上进行了旋转
     *
     * @param target
     * -10^4 <= target <= 10^4
     */
    public int search(int[] nums, int target) {
        int len = nums.length, left = 0, right = len - 1;
        int rotateLen = 1;
        while (rotateLen < nums.length && nums[rotateLen] > nums[rotateLen - 1]){
            rotateLen++;
        }
        while (left <= right){
            int mid = (left + right) / 2;
            int midIndex = mid + rotateLen;
            if (midIndex >= len){
                midIndex = midIndex - len;
            }
            int val = nums[midIndex];
            if (val < target){
                left = mid + 1;
            } else if (val > target){
                right = mid - 1;
            } else {
                return midIndex;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = { 1, 3};
        int target = 2;
        int search = new SearchInRotatedSortedArray().search(nums, target);
        System.out.println(search);
        Assert.isTrue(search == 1);
    }

}
